package net.takela.common.utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Maps {

    private Maps() {}

    /**
     * 根据list中元素的一个值，将list转为Map
     *
     * @param list
     * @param fn
     * @return
     */
    public static <T, R> Map<R, T> transform(List<T> list, Function<T, R> fn) {
        return list.stream().collect(Collectors.toMap(fn, e -> e, (a, b) -> b));
    }

    public static <T, R> Map<R, List<T>> groupBy(List<T> list, Function<T, R> fn) {
        return list.stream().collect(Collectors.groupingBy(fn));
    }

    public static <K, V> Map<K, V> of(K key, V value) {
        Map<K, V> map = new HashMap<>();
        map.put(key, value);
        return map;
    }
}
